<template>
    <div v-loading="globalLoading" loading-tip="请耐心等待，请勿刷新页面">
        <a-modal
            title="同步飞书"
            centered
            v-model:visible="visible"
            :width="1000"
            :bodyStyle="{ height: '600px', overflow: 'hidden' }"
            @cancel="handleCancel"
        >
            <div>
                <flexbox align="flex-start">
                    <a-form layout="inline" ref="ruleFormRef" :model="form" :rules="rules">
                        <a-row>
                            <a-col :span="8">
                                <a-form-item label="所属产品">
                                    <SelectCatalogCode :changeOnSelect="true" v-model:value="form.catalogCode" />
                                </a-form-item>
                            </a-col>
                            <a-col :span="8">
                                <a-form-item label="状态">
                                    <h-dic-select
                                        bordered
                                        type="productRequireStatus"
                                        v-model:value="form.status"
                                        :getPopupContainer="(node) => node.parentNode.parentNode.parentNode.parentNode.parentNode"
                                        v-if="visible"
                                    />
                                </a-form-item>
                            </a-col>
                            <a-col :span="8">
                                <a-form-item label="产品负责人">
                                    <a-input v-model:value="form.createUser" />
                                </a-form-item>
                            </a-col>
                            <a-col :span="8">
                                <a-form-item label="类型">
                                    <h-dic-select
                                        bordered
                                        type="requireType"
                                        v-model:value="form.requireType"
                                        :getPopupContainer="(node) => node.parentNode.parentNode.parentNode.parentNode.parentNode"
                                        v-if="visible"
                                    />
                                </a-form-item>
                            </a-col>
                            <a-col :span="8">
                                <a-form-item label="版本号" name="type">
                                    <a-input v-model:value="form.relateVersionNumber" />
                                </a-form-item>
                            </a-col>
                            <a-col :span="8">
                                <a-form-item label="需求编号" name="type">
                                    <a-input v-model:value="form.requireNumber" />
                                </a-form-item>
                            </a-col>
                            <a-col :span="12">
                                <a-form-item label="创建时间" name="type">
                                    <h-range-picker-cell
                                        :value="[
                                            form.createTime ? $moment(form.createTime, 'YYYY-MM-DD') : null,
                                            form.createTimeEnd ? $moment(form.createTimeEnd, 'YYYY-MM-DD') : null,
                                        ]"
                                        @change="rangeDateChange"
                                    />
                                </a-form-item>
                            </a-col>
                        </a-row>
                    </a-form>
                    <a-button style="margin-left: 24px" type="primary" @click="handleSearch">查询</a-button>
                </flexbox>

                <div class="margin-t-8">
                    <CustomTable
                        :scroll="{ x: 'max-content', y: 340 }"
                        rowKey="id"
                        size="small"
                        :loading="loading"
                        :columns="tableColumns"
                        :data-source="list"
                        :pagination="paginationConfig"
                        :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
                        @change="handleTableChange"
                    >
                        <template #requireType="{ record }">
                            <HProductType :type="$filters.valToNameFilter('requireType', record.requireType)" />
                        </template>
                        <template #status="{ record }">
                            <HStatusBadge :status="record.status" />
                        </template>
                    </CustomTable>
                </div>
            </div>
            <template #footer>
                <a-button @click="handleCancel">取消</a-button>
                <a-button :disabled="!(allSelectedRows && allSelectedRows.length)" class="margin-l-8" type="primary" @click="handleSync"
                    >同步需求</a-button
                >
            </template>
        </a-modal>
    </div>
</template>

<script lang="ts">
import uuid from 'node-uuid';
import api from '@/api';
import store from '@/store';
import { useMessage } from '@/hooks/common/useMessage';
import { CustomTable } from '@/components';
import { HSearchSelectCell } from '@/components';
import SelectCatalogCode from './SelectCatalogCode.vue';
import { SmileOutlined } from '@ant-design/icons-vue';
import { DownOutlined, UpOutlined } from '@ant-design/icons-vue';
import { message } from 'ant-design-vue/es';
import { useTableRowSelect } from '@/components/Table/hooks/index';
import { HCustomSelect, HDicSelect, HShowMoreSelect, HRangePickerCell, HSuggestInput, HProductType, HStatusBadge } from '@/components';
import { defineComponent, ref, unref, reactive, toRefs, computed, onBeforeUnmount } from 'vue';
export default defineComponent({
    components: {
        DownOutlined,
        UpOutlined,
        HSearchSelectCell,
        SmileOutlined,
        CustomTable,
        HCustomSelect,
        HDicSelect,
        HShowMoreSelect,
        HRangePickerCell,
        HSuggestInput,
        HProductType,
        HStatusBadge,
        SelectCatalogCode
    },
    props: {
        detail: {
            type: Object,
            default: () => ({})
        },
        info: {
            type: Object,
            default: () => ({})
        }
    },
    emits: ['success'],
    setup() {
        const { selectedRowKeys, allSelectedRows, onSelectChange, setSelectRows } = useTableRowSelect();
        const { createConfirm } = useMessage();
        const ruleFormRef = ref<any>();
        const rules = {
            name: [{ required: true, message: '模板名称不能为空', trigger: 'blur' }]
        };
        const tableColumns = [
            {
                title: '需求编号',
                dataIndex: 'requireNumber',
                width: 200,
                fixed: 'left'
            },
            {
                title: '需求名称',
                dataIndex: 'requireName',
                width: 400
            },
            {
                title: '类型',
                dataIndex: 'requireType',
                width: 100,
                slots: { customRender: 'requireType' }
            },
            {
                title: '状态',
                dataIndex: 'status',
                width: 100,
                slots: { customRender: 'status' }
            },
            {
                title: '产品负责人',
                dataIndex: 'createUser',
                width: 100
            },
            {
                title: '预发布版本号',
                dataIndex: 'relateVersionNumber',
                width: 100
            }
        ];
        const state = reactive<any>({
            visible: false,
            mySystem: [],
            checkedSystemList: [],
            isShowMoreSystemBtn: false, // 是否显示更多按钮
            fsTableOptions: [],
            form: {
                catalogCode: '',
                status: '',
                requireType: '',
                createUser: '',
                relateVersionNumber: '',
                createTime: '',
                createTimeEnd: '',
                requireNumber: ''
            },
            list: [],
            paginationConfig: {
                total: 0,
                pageSize: 20, // 每页中显示10条数据
                showSizeChanger: true,
                pageSizeOptions: ['5', '10', '15', '20', '50'], // 每页中显示的数据
                showTotal: (total: number) => `共有 ${total} 条数据`, // 分页中显示总的数据
                current: 1
            },
            checkedProductIds: [],
            detail: {},
            loading: false,
            globalLoading: false,
            uuid: '',
            timer: null
        });
        const rowSelection = computed(() => {
            return {
                selectedRowKeys: state.checkedProductIds,
                onChange: (selectedRowKeys, selectedRows) => {
                    state.checkedProductIds = selectedRowKeys;
                    console.log('aa', selectedRows);
                }
            };
        });
        const resetForm = () => {
            state.form = {
                catalogCode: '',
                status: '',
                requireType: '',
                createUser: '',
                relateVersionNumber: '',
                createTime: '',
                createTimeEnd: '',
                requireNumber: ''
            };
        };
        const open = (detail) => {
            state.detail = detail;
            state.visible = true;
            resetForm();
            if (state.detail.id) {
                Object.keys(state.form).forEach((key) => {
                    state.form[key] = state.detail[key];
                });
            }
            state.form.createTime = '';
            getList();
        };
        const handleCancel = () => {
            state.visible = false;
        };
        const handleTableChange = (val) => {
            state.paginationConfig = val;
            getList();
        };
        const getList = async () => {
            state.loading = true;
            const { success, moule, totalCount } = await api.productRequireModel.selectPage({
                pageNum: state.paginationConfig.current,
                pageSize: state.paginationConfig.pageSize,
                admin: store.getters.userInfo.roles.some((item) => ['admin', '观察者', '领导', '产品管理委员会'].includes(item)) ? 1 : 0,
                ...state.form,
                selectType: 'pool'
            });
            if (success) {
                state.list = [...moule];
                state.paginationConfig.total = totalCount;
            }
            state.loading = false;
        };

        const handleSync = async () => {
            state.uuid = `feishu:${uuid.v4()}`;
            const query = {
                id: state.detail.id,
                redisKey: state.uuid,
                pmpProductRequireDTOS: [...unref(allSelectedRows)]
            };
            state.globalLoading = true;
            const { success, errorMsg } = await api.fsFileSyncTmplModel.syncRecordsToTable(query);
            if (success) {
                getRedisFeishu();
                state.timer = setInterval(() => {
                    getRedisFeishu();
                }, 5000);
            } else {
                message.error(errorMsg);
                state.globalLoading = false;
            }
        };
        const getRedisFeishu = async () => {
            const query = {
                key: state.uuid
            };
            const { success, moule } = await api.fsFileSyncTmplModel.getRedisValue(query);
            if (success && moule) {
                if (state.timer) {
                    clearInterval(state.timer);
                    state.timer = null;
                }
                createConfirm({
                    title: '提示',
                    content: moule,
                    iconType: 'success',
                    okText: '关闭',
                    keyboard: false,
                    cancelButtonProps: { style: { display: 'none' } }
                });
                state.globalLoading = false;
                setSelectRows([], []);
            }
        };
        const handleSearch = () => {
            state.paginationConfig.current = 1;
            getList();
        };

        const rangeDateChange = (val) => {
            const { startTime, endTime } = val;
            state.form.createTime = startTime;
            state.form.createTimeEnd = endTime;
        };

        // 离开页面前取消定时器
        onBeforeUnmount(() => {
            if (state.timer) {
                clearInterval(state.timer);
                state.timer = null;
            }
        });
        return {
            tableColumns,
            ruleFormRef,
            rules,
            ...toRefs(state),
            selectedRowKeys,
            allSelectedRows,
            open,
            handleCancel,
            handleTableChange,
            rowSelection,
            handleSync,
            handleSearch,
            onSelectChange,
            rangeDateChange
        };
    }
});
</script>

<style scoped lang="less">
::v-deep(.section-wrap) {
    padding: 0 24px !important;
}
</style>